package com.retail.lottery.colalottery.job.notice.service;

import cn.hutool.json.JSONUtil;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.retail.lottery.colalottery.constant.RedisConstant;
import com.retail.lottery.colalottery.entity.*;
import com.retail.lottery.colalottery.enums.DeleteStatusEnum;
import com.retail.lottery.colalottery.enums.MessageNoticeStatusEnum;
import com.retail.lottery.colalottery.enums.NoticeTypeEnum;
import com.retail.lottery.colalottery.enums.OrderCallbackSyncStatusEnum;
import com.retail.lottery.colalottery.job.node.RedisNodeIpManager;
import com.retail.lottery.colalottery.service.*;
import com.retail.lottery.colalottery.service.cola.ColaClientService;
import com.retail.lottery.colalottery.utils.DateUtil;
import com.retail.lottery.colalottery.utils.RedisUtils;
import com.retail.lottery.colalottery.vo.MessageNoticeVo;
import com.retail.lottery.colalottery.vo.NodeInfoVo;
import com.retail.lottery.colalottery.vo.request.GetLotteryTimesRequest;
import com.retail.lottery.colalottery.vo.request.SendMessageNoticeRequest;
import com.retail.lottery.colalottery.vo.response.GetLotteryTimesResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Slf4j
@Service
public class BbqMessageNoticeCommonService extends RedisNodeIpManager {
    @Value("${api-bbq-client-campaignCode}")
    private String campaignCode;
    @Value("${api-bbq-client-buCode}")
    private String buCode;
    @Value("${api-bbq-client-setupId}")
    private String setupId;
    private static final LocalDateTime ActivityFinishTime = LocalDateTime.of(2025, 9, 18, 9, 0);
    private static final LocalDateTime ActivityStartTime = LocalDateTime.of(2025, 8, 6, 9, 0);
    @Resource
    private MessageNoticeRecordService messageNoticeRecordService;
    @Resource
    private NoticeTemplateService noticeTemplateService;
    @Resource
    private WechatCustomerService wechatCustomerService;
    @Resource
    private ColaClientService colaClientService;
    @Resource
    private OrderCallbackService orderCallbackService;
    @Resource
    private OrderDetailService orderDetailService;

    public void createNotice() {
        NodeInfoVo nodeInfoVo = localNodeInfo();
        int shardingTotalCount = nodeInfoVo.getNodeNum();
        int shardingItem = nodeInfoVo.getCurrentNode();
        //log.info("创建订阅消息通知记录Job，任务总片数: {}, 当前分片项: {}", shardingTotalCount, shardingItem);
        //2.2.1创建生成抽奖通知消息(每周五提醒)
        String redisKey = String.format(RedisConstant.REDIS_KEY_BBQ_MESSAGE_NOTICE_CREATE, shardingTotalCount, shardingItem);
        if (!RedisUtils.saveNX(redisKey, "1", 30, TimeUnit.SECONDS)) {
            log.info("BBQ创建订阅消息通知记录Job，任务总片数: {}, 当前分片项: {}, 数据处理正在执行中，未获取锁", shardingTotalCount, shardingItem);
            return;
        }

        try {
            List<WechatCustomer> callbacks = wechatCustomerService.getBaseMapper()
                    .selectList(new LambdaQueryWrapper<WechatCustomer>()
                    .eq(WechatCustomer::getMessageFlag, DeleteStatusEnum.no_del.getCode())
                    .last(" order by id asc limit 100"));
            //多节点的话，此处要以user分片
            if (CollectionUtils.isEmpty(callbacks)) {
                log.info("BBQ创建订阅消息通知记录Job，任务总片数: {}, 当前分片项: {}, 当前无待处理数据", shardingTotalCount, shardingItem);
                return;
            }
            //根据encryptMobile进行分组
            List<WechatCustomer> groupByHash = callbacks.stream().filter(callback -> {
                int dataShardingItem = callback.getId().hashCode() % shardingTotalCount;
                dataShardingItem = dataShardingItem < 0 ? (dataShardingItem * -1) : dataShardingItem;
                return dataShardingItem == shardingItem;
            }).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(groupByHash)) {
                log.info("BBQ创建订阅消息通知记录Job，任务总片数: {}, 当前分片项: {}, 当前分片无待处理数据", shardingTotalCount, shardingItem);
                return;
            }
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime newTime = now.plusMinutes(30);
            for (WechatCustomer wechatCustomer : groupByHash) {
                List<LocalDateTime> everyFridayTimeList = DateUtil.getFridayAtTenListFromEndDate(newTime, ActivityStartTime, ActivityFinishTime);
                for (LocalDateTime fridayAtTen : everyFridayTimeList) {
                    createMessageInfo(wechatCustomer, shardingTotalCount, shardingItem, fridayAtTen);
                }
                wechatCustomer.setMessageFlag(DeleteStatusEnum.del.getCode());
                wechatCustomerService.updateById(wechatCustomer);
            }
        } catch (Exception e) {
            log.error("BBQ创建订阅消息通知记录Job，任务总片数: {}, 当前分片项: {}, 创建通知消息Job异常", shardingTotalCount, shardingItem, e);
        } finally {
            RedisUtils.del(redisKey);
        }


    }

    private void createMessageInfo(WechatCustomer customer, int shardingTotalCount, int shardingItem, LocalDateTime fridayAtTen) {
        try {
            log.info("创建订阅消息通知记录Job，任务总片数: {}, 当前分片项: {}, 开始创建通知消息：{}", shardingTotalCount, shardingItem, customer.getId());
            LocalDateTime now = LocalDateTime.now();
            //2.查询对应模版信息
            MessageNoticeRecord lotteryMessageNotice = new MessageNoticeRecord();
            lotteryMessageNotice.setBuCode(buCode);
            lotteryMessageNotice.setSetupId(setupId);
            lotteryMessageNotice.setEncryptMobile(customer.getEncryptMobile());
            lotteryMessageNotice.setWechatCustomerId(customer.getId());
            lotteryMessageNotice.setThresholdOrderId(null);
            lotteryMessageNotice.setThresholdValue(0L);//   单位：分
            lotteryMessageNotice.setThresholdLevel(0);
            lotteryMessageNotice.setLotteryNum(0);
            NoticeTemplate noticeTemplateId = noticeTemplateService.getNoticeTemplateId(buCode, setupId, NoticeTypeEnum.QUESTION.getType());
            lotteryMessageNotice.setNoticeTemplateId(noticeTemplateId.getId());
            lotteryMessageNotice.setNoticeStatus(MessageNoticeStatusEnum.WAIT.getStatus());
            Date newDate = Date.from(fridayAtTen.atZone(ZoneId.systemDefault()).toInstant());
            lotteryMessageNotice.setNoticeDate(newDate);
            messageNoticeRecordService.save(lotteryMessageNotice);
        } catch (Exception e) {
            log.error("创建活动预约通知消息Job异常，订单ID:{}", customer.getId(), e);
        }
    }

}
